package yicheng.dinnertogetherapp;


import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ContactInfoActivity extends Activity{

	private boolean isUsingApp;

	private String contact_name;
	private String contact_number;


	private Button contact_info_call_button, contact_info_text_button, contact_info_invite_call_button, contact_info_send_request_button;
	private TextView contact_name_textView, contact_info_phoneNumber_textView;
	private LinearLayout contact_info_button_layout;

	private HashMap<String, String> myOnlineFriendList = new HashMap<String, String>(FriendListActivity.onlineFriendList);
	private HashMap<String, String> myOfflineFriendList =  new HashMap<String, String>(FriendListActivity.offlineFriendList);


	public static SharedPreferences local_user_information;
	private SharedPreferences.Editor local_user_editor;
	private String PREFS_NAME = "LocalUserInfo";

	public static AmazonClientManager clientManager;

	private String PHONE_NUMBER, NICKNAME;

	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact_info_layout);
		overridePendingTransition(R.anim.activity_left_in, R.anim.activity_left_out);


		contact_name_textView = (TextView) findViewById(R.id.contact_name_textView);
		contact_info_phoneNumber_textView = (TextView) findViewById(R.id.contact_info_phoneNumber_textView);

		contact_info_call_button = (Button) findViewById(R.id.contact_info_call_button);
		contact_info_text_button = (Button) findViewById(R.id.contact_info_text_button);
		contact_info_invite_call_button = (Button) findViewById(R.id.contact_info_invite_call_button);
		contact_info_send_request_button = (Button) findViewById(R.id.contact_info_send_request_button);

		contact_info_button_layout = (LinearLayout) findViewById(R.id.contact_info_button_layout);
		

		clientManager = new AmazonClientManager();
		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");


		Intent intent = getIntent();
		Bundle registerInfoData = intent.getBundleExtra("contactInfo");
		contact_number = registerInfoData.getString("contact_info_number");
		contact_name = registerInfoData.getString("contact_info_name");

		isUsingApp = registerInfoData.getBoolean("is_using_app");




		setHandlerControl();


		setContactInfoDisplay();





	}

	private void setHandlerControl(){
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == 3){
					Toast.makeText(getApplicationContext(), "Friend request sent successfully", Toast.LENGTH_SHORT).show();
					finish();
					overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
				}

				if (msg.what == 4){

					AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(ContactInfoActivity.this);
					dialogBuilder.setTitle("Add Friend");
					dialogBuilder.setMessage("The friend you searched has already sent you a request, do you want to see your request?");
					dialogBuilder.setCancelable(true);
					dialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which)  {
							// TODO Auto-generated method stub
							Intent gotoFriendRequestListIntent = new Intent("yicheng.dinnertogetherapp.FRIENDREQUESTLISTACTIVITY");
							startActivity(gotoFriendRequestListIntent);

						}
					});



					dialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which)  {
							// TODO Auto-generated method stub
							dialog.cancel();
						}
					});

					AlertDialog dialog = dialogBuilder.create();
					dialog.show();
				}



			}
		};




	}



	private void setContactInfoDisplay(){
		contact_name_textView.setText(contact_name);
		contact_info_phoneNumber_textView.setText(contact_number);

		if (isUsingApp){
			contact_info_call_button.setVisibility(View.VISIBLE);
			contact_info_button_layout.setVisibility(View.VISIBLE);
			contact_info_invite_call_button.setVisibility(View.INVISIBLE);
			contact_info_send_request_button.setText("Add as your friend");
			setCallButtonControl(isUsingApp);
			setTextButtonControl(isUsingApp);
			setAddFriendButtonControl();

		}
		else{
			contact_info_button_layout.setVisibility(View.INVISIBLE);
			contact_info_send_request_button.setVisibility(View.VISIBLE);
			contact_info_invite_call_button.setVisibility(View.VISIBLE);
			contact_info_send_request_button.setText("Invite to use eatogether");
			setCallButtonControl(isUsingApp);
			setTextButtonControl(isUsingApp);
		}
	}


	private void setAddFriendButtonControl(){
		contact_info_send_request_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (myOnlineFriendList.containsKey(contact_number) || myOfflineFriendList.containsKey(contact_number) ){
					Toast.makeText(getApplicationContext(), "The number is already your friend!", Toast.LENGTH_SHORT).show();
				}
				else{


					AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(ContactInfoActivity.this);
					dialogBuilder.setTitle("Add Friend");
					dialogBuilder.setMessage("Send a friend request?");
					dialogBuilder.setCancelable(true);
					dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which)  {
							// TODO Auto-generated method stub

							if (isConnectedToInternet()){
								sendFriendRequest();
								dialog.cancel();
							}
							else{
								Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
								dialog.cancel();
							}
						}
					});



					dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which)  {
							// TODO Auto-generated method stub
							dialog.cancel();
						}
					});

					AlertDialog dialog = dialogBuilder.create();
					dialog.show();




				}
			}
		});

	}





	private void sendFriendRequest(){
		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		NICKNAME = local_user_information.getString("Nickname", "default");

		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub

						HashMap<String, String> myFriendRequestList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_REQUEST_LIST_ITEM);

						if (myFriendRequestList.containsKey(contact_number)){
							Message msg = Message.obtain();
							msg.what = 4;
							handler.sendMessage(msg);
						}
						else{

							HashMap<String, String> searchedFriendFriendRequestList = SimpleDB.getAttributesForItem(clientManager, contact_number, SimpleDB.FRIEND_REQUEST_LIST_ITEM);

							searchedFriendFriendRequestList.put(PHONE_NUMBER, NICKNAME);

							SimpleDB.updateAttributesForItem(clientManager, contact_number,  SimpleDB.FRIEND_REQUEST_LIST_ITEM, searchedFriendFriendRequestList);

							Message msg = Message.obtain();
							msg.what = 3;
							handler.sendMessage(msg);

						}




					}

				}).start();
			}

		});
	}













	private void setCallButtonControl(boolean isUsingApp){

		PhoneCallListener phoneListener = new PhoneCallListener();
		TelephonyManager telephonyManager = (TelephonyManager) ContactInfoActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
		telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);

		if (isUsingApp){
			contact_info_call_button.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					callFriend();

				}
			});
		}
		else{
			contact_info_invite_call_button.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					callFriend();

				}
			});
		}
	}


	private void setTextButtonControl(boolean isUsingApp){
		if (isUsingApp){
			contact_info_text_button.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					textFriend("");
				}
			});
		}
		else{
			contact_info_send_request_button.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					textFriend("I am using Eatogether app, download it at http://sdfaljlk.com");
				}
			});
		}
	}



	private void textFriend(String message){
		Log.i("Send SMS", "");

		Intent smsIntent = new Intent(Intent.ACTION_VIEW);
		smsIntent.setData(Uri.parse("smsto:"));
		smsIntent.setType("vnd.android-dir/mms-sms");

		smsIntent.putExtra("address"  , contact_number);
		smsIntent.putExtra("sms_body"  , message);
		try {
			startActivity(smsIntent);

			Log.i("Finished sending SMS...", "");
		} catch (android.content.ActivityNotFoundException ex) {
			Toast.makeText(ContactInfoActivity.this, 
					"SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
		}
	}





	private void callFriend(){

		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(ContactInfoActivity.this);
		dialogBuilder.setTitle("Make a call");

		String message = "Are you sure you want to call " + contact_name + "("+ contact_number + ")?" ;
		dialogBuilder.setMessage(message);
		dialogBuilder.setCancelable(true);
		dialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {


				Uri number = Uri.parse("tel:" + contact_number);
				Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
				startActivity(callIntent);

				dialog.cancel();



			}
		});

		dialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {

				dialog.cancel();

			}
		});

		AlertDialog dialog = dialogBuilder.create();
		dialog.show();
	}





	private class PhoneCallListener extends PhoneStateListener {

		private boolean isPhoneCalling = false;

		String LOG_TAG = "LOGGING 123";

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {

			if (TelephonyManager.CALL_STATE_RINGING == state) {
				// phone ringing
				Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
			}

			if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
				// active
				Log.i(LOG_TAG, "OFFHOOK");

				isPhoneCalling = true;
			}

			if (TelephonyManager.CALL_STATE_IDLE == state) {
				// run when class initial and phone call ended, 
				// need detect flag from CALL_STATE_OFFHOOK
				Log.i(LOG_TAG, "IDLE");

				if (isPhoneCalling) {

					Log.i(LOG_TAG, "restart app");

					// restart app
					Intent i = getBaseContext().getPackageManager()
							.getLaunchIntentForPackage(
									getBaseContext().getPackageName());
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);

					isPhoneCalling = false;
				}

			}
		}
	}




	private boolean isConnectedToInternet(){
		ConnectivityManager connectivityManager = 
				(ConnectivityManager)ContactInfoActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo wifi_network = 
				connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo mobile_network = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		//Only for testing
		return wifi_network.isConnectedOrConnecting() || mobile_network.isConnectedOrConnecting();
		/*return  mobile_network.isConnectedOrConnecting();*/
	}



	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
	}


}
